package emu.decvices.cartridge.mappers;

import emu.decvices.bus.BusDevice;
import emu.decvices.cartridge.Cartridge;

public class Mapper002 extends Mapper{
    public Mapper002(Cartridge cartridge) {
        super(cartridge);
    }

    @Override
    public BusDevice getCpuDevice() {
        return new CpuDevice();
    }

    @Override
    public BusDevice getPpuDevice() {
        return new PpuDevice();
    }

    private class PpuDevice extends BusDevice{
        @Override
        public int fromDeviceRead(int address) {
            if(address>=0x0000&&address<=0x1FFF){
                return chrData[address]&0xFF;
            }
            return -1;
        }

        @Override
        public boolean toDeviceWrite(int address, int data) {
            if (address >= 0x0000 && address <= 0x1FFF) {
                chrData[address] = (byte) (data & 0xFF);
                return true;
            }
            return false;
        }
    }

    private class CpuDevice extends BusDevice{
        private int bank;
        private int lastBankIndex = (romHeader.getPrgRomChunks()-1)*0x4000;
        @Override
        public int fromDeviceRead(int address) {
            //CPU可寻址prgRom的总线地址范围
            if(address>=0x8000 && address<=0xBFFF) {
                return prgData[bank*0x4000+(address&0x3FFF)]&0xFF;
            }else if(address>=0xC000 && address<=0xFFFF){
                return prgData[lastBankIndex+(address&0x3FFF)]&0xFF;
            }
            return -1;
        }

        @Override
        public boolean toDeviceWrite(int address, int data) {
            if(address>=0x8000&&address<=0xFFFF){
                bank = data&0xF;
                return true;
            }
            return false;
        }
    }
}
